/**
 * Created by Peter Bortchagovsky.
 * 26.01.12 12:03
 */


if(jQuery) (function($){

	window.koatuu = {};

	$.fn.link_select = function(options) {
		var $els = this;

		options = $.extend({
			  zero_string: ''
			, add_zero: true
//			, selector: '[linked]'
			, attr: 'linked'
			, url: '?id='
//			, base: ''
//			, param: 'id'
			// url = base + '?' + param + '=' + $el.val()
		}, options);

		var find_linked = function($with, once) {
			var $collection;
			if ($with.attr('id')) {
				$('*[' + options.attr + '=' + $with.attr('id') + ']').each(function() {
					if (!$collection) $collection = $(this);
					else $collection.add( $(this) );

					if (!once) $collection = $collection.add( find_linked( $(this) ) );
				});
			}
			return $collection || $();
		};

		var process_data = function($el, json) {
			if (!window.koatuu[$el.val()]) window.koatuu[$el.val()] = json;
			find_linked($el, 'once').each(function() {
				$(this).attr({disabled: false});
				for(var id in json) {
					$(this).append($('<OPTION>').val(id).html(json[id]['name']))
				}
			});
		};

		var process_linked = function(e) {
			var $el = $(e.target);
			find_linked($el).attr({disabled: true}).html(options.add_zero ? $('<OPTION>').val('').html(options.zero_string) : '');
			if ($el.val()) {
				if (!window.koatuu[$el.val()]) $.getJSON(options.url + $el.val(), function(json) {process_data($el, json)});
				else process_data( $el,  window.koatuu[$el.val()] );
			}
		};

		$els.on('change', process_linked);
	}

})(jQuery)